package cn.com.api.service.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.com.api.entity.ApiDingDan;
import cn.com.api.entity.ApiGoods;
import cn.com.api.entity.ApiShop;
import cn.com.api.entity.ApiT_erp_log;
import cn.com.api.entity.ApiT_erp_log_hist;
import cn.com.api.entity.ApiT_products;
import cn.com.api.mapper.ApiDingDanMapper;
import cn.com.api.mapper.ApiGoodsMapper;
import cn.com.api.mapper.ApiShopsMapper;
import cn.com.api.mapper.ApiT_cityMapper;
import cn.com.api.mapper.ApiT_erp_logMapper;
import cn.com.api.mapper.ApiT_erp_log_histMapper;
import cn.com.api.mapper.ApiT_productsMapper;
import cn.com.api.resultpage.CarOrderPage;
import cn.com.api.service.ApiCarService;
import cn.com.api.service.ApiErpService;
import cn.com.api.service.ApiT_productsService;
import cn.com.api.service.StartOnLoadService;
import cn.com.util.Tools;
import cn.com.util.*;
import cn.com.util.*;
import net.sf.ehcache.Cache;
import net.sf.ehcache.Element;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service
public class ApiErpServiceImpl
		implements ApiErpService {
	@Autowired
	private ApiT_productsService apiT_productsService;
	
	@Autowired
	private ApiT_productsMapper apiT_productsMapper;
	@Autowired
	private ApiT_cityMapper apiT_cityMapper;
	@Autowired
	private ApiShopsMapper apiShopsMapper;
	@Autowired
	private ApiDingDanMapper apiDingDanMapper;
	@Autowired
	private ApiCarService apiCarService;
	@Autowired
	private StartOnLoadService sartOnLoadService; 
	@Autowired
	private ApiT_erp_logMapper apiT_erp_logMapper;
	@Autowired
	private ApiT_erp_log_histMapper apiT_erp_log_histMapper;
	@Autowired
	private ApiGoodsMapper apiGoodsMapper;
	
	private static Logger logger = Logger.getLogger(ApiErpServiceImpl.class);
	
	@Override
	public ApiT_products queryByGoodsId4erp(Integer goods_id) {
		ApiT_products t_products = apiT_productsMapper
				.queryByGoodsId4erp(goods_id);
		return t_products;
	}

	// 添加erp
	@Override
	public long insertT_products4erp(ApiT_products t_products){
		long ret_I= apiT_productsMapper.insertT_products4erp(t_products);
		return ret_I;
	}
	
	// 更新erp货品信息
	@Override
	public int updateT_products4erp(ApiT_products t_products){
		int ret_I= apiT_productsMapper.updateT_products4erp(t_products);
		return ret_I;
	}
	
	
	/**
	 *ERP货品库存
	 */
	public void updateT_productsStock4erp() {
		System.out.println("ERP货品库存！");
		String nowDate = new SimpleDateFormat("yyyy-MM-dd").format(new Date());

		HttpClient httpclient = new DefaultHttpClient();  
		String erp_service = sartOnLoadService.dictionaryMap().get("ERP_SERVICE");
        String erpUrl="http://139.196.106.94:8090/Services.ashx";  
        HttpPost httppost = new HttpPost(erpUrl);  
        String strResult = "";  
          
        try {             
            Map<String, String> map = new TreeMap<String, String>();
            map.put("sToken", this.tokenGet());
            map.put("querType", null);
            map.put("action", "GoodsStock");
            map.put("sBranchNo", "001");    
            map.put("iPageIndex", "1");
            map.put("iPageSize", "100");
            
            //map.put("goodsId", "00000001");
            //遍历集合
            String strString1 = "";	
            for (Iterator<String> it = map.keySet().iterator(); it.hasNext();) {
            	String _key = it.next();
            	strString1 +="&" + _key +"="+ map.get(_key);
            }  
            // 生成ERP md5 
            strString1 = strString1.substring(1);
            String strTemp = strString1.toUpperCase();
            String strTempMd5 = Tools.erpMD5(strTemp).toUpperCase();
            map.put("sMd5", strTempMd5);
       
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
            nameValuePairs.add(new BasicNameValuePair("param", JsonUtil.object2json(map)));            
            String[] str_list = {"00000001","00000002"};
            nameValuePairs.add(new BasicNameValuePair("goodsIds", JsonUtil.object2json(str_list)));            
            
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
			//
			HttpResponse response = null;
			response = httpclient.execute(httppost);
 
            if (response.getStatusLine().getStatusCode() == 200) {  
                /*读返回数据*/  
                String conResult = null;
				conResult = EntityUtils.toString(response.getEntity());
		
                JSONObject sobj = new JSONObject();  
                sobj = sobj.fromObject(conResult);  
                 
                String code = sobj.getString("bResult");  
                String error = sobj.getString("sCode");  
                String sError = sobj.getString("sError");  
                String result = sobj.getString("gdsStocks");
                
            }
        } catch (Exception e) {  
        	e.printStackTrace();  
        } 
	          
	}
	
	/**
	 *ERP订单新增定时检查
	 */
	public void addOrder4erpTask() {
		List<ApiDingDan> orders = apiDingDanMapper.searchNewOrdersPaid();
		
		for(ApiDingDan dd: orders){
			// 根据订单号查询订单---已经查出来，不需要再查询一遍
			// ApiDingDan dingDan = apiDingDanMapper.searchDingDanByTitleId(dd.getTitles());
			if (dd != null) {
				List<ApiT_erp_log_hist> hist_order = apiT_erp_log_histMapper.findT_erp_log_histsByOrder_id(dd.getTitles());
				if(hist_order.size()<=0){
					this.addOrder4erp(dd);
				}
			}
		}
	}
	
	/**
	 *ERP订单新增
	 */
	public void addOrder4erp(ApiDingDan order_info) {
	
		HttpClient httpclient = new DefaultHttpClient();  
		String erp_service = sartOnLoadService.dictionaryMap().get("ERP_SERVICE");
        String erpUrl="http://139.196.106.94:8090/Services.ashx";  
        HttpPost httppost = new HttpPost(erp_service);  
        String strResult = "";  
          
        try {             
            Map<String, Object> map = new TreeMap<String, Object>();
            map.put("sToken", this.tokenGet());
            map.put("action", "wholesalersorder");
            map.put("oid", order_info.getTitles().trim());    
            map.put("orderTime", (order_info.getAppdate().getTime())/1000);
            map.put("orderMoney", order_info.getMoney() );
            //分站id对应仓库id
            ApiShop shop = apiShopsMapper.findT_shopsById(order_info.getShop_id());
            map.put("branchNo", "00" + shop.getC_city_id().toString());
            map.put("oderType", "1");
            map.put("voucherId", "1");
            map.put("payAmt", order_info.getMoney());
            map.put("payType", "001");    
            map.put("custNo", "100" + shop.getC_city_id().toString());	//erp要求写死

			List<Map<String, Object>> goods_list = new ArrayList<Map<String, Object>>();
            
            List<CarOrderPage> productList = new ArrayList<CarOrderPage>();
			productList = apiCarService.searchCarProductsByCids(order_info.getCar_ids());
			for(CarOrderPage cart: productList){
	            Map<String, Object> map_goods = new TreeMap<String, Object>();
	            
	            map_goods.put("money", cart.getPrice() );
	            map_goods.put("orderCnt", cart.getCount()); 
	            //goodsId 是ERP商品内部码
	            map_goods.put("goodsId", cart.getProduct_id().toString().substring(1));
	            map_goods.put("barcode", cart.getErp_product_id());
	            map_goods.put("itemsubno", cart.getErp_product_id());
	            map_goods.put("unit", cart.getUnit());
	            goods_list.add(map_goods);
			}
            map.put("orderDetails", JsonUtil.object2json(goods_list).trim());
            String str_order_name = order_info.getName().replace("￥", "");
            String str_address = order_info.getAddress().replace("￥", "");
            String str_mobile = order_info.getMobile();
            String str_remark= order_info.getBz();
            map.put("memo", "姓名||"+ str_order_name +"￥地址||"+ str_address+"￥联系电话||" +str_mobile+"￥备注||"+str_remark  );
            
            //遍历集合
            String strString1 = "";	
            for (Iterator<String> it = map.keySet().iterator(); it.hasNext();) {
            	String _key = it.next();
            	strString1 +="&" + _key +"="+ map.get(_key);
            }  
            //生成ERP md5 
            strString1 = strString1.substring(1);
            String strTemp = strString1.toUpperCase();
            String strTempMd5 = Tools.erpMD5(strTemp).toUpperCase();
            map.put("sMd5", strTempMd5);
           
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
            nameValuePairs.add(new BasicNameValuePair("param", JsonUtil.object2json(map)));  
       
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
			//
			HttpResponse response = null;
			response = httpclient.execute(httppost);
			logger.error("erp调用返回编码："+response.getStatusLine().getStatusCode());
            if (response.getStatusLine().getStatusCode() == 200) {  
            	logger.error("erp调用返回成功！");
                /*读返回数据*/  
                String conResult = null;
				conResult = EntityUtils.toString(response.getEntity());
		
                JSONObject sobj = new JSONObject();  
                sobj = sobj.fromObject(conResult);  
                
                String bResult = sobj.getString("bResult"); 
                logger.error("erp调用返回成功-返回bResult-"+bResult);
                // add by @RuanCong 2016/03/01 防止不停地输出报错信息
                if (bResult != null && bResult.equals("false")){
                	return;
                }
                String sCode = sobj.getString("sCode");  
                String sError = sobj.getString("sError");  
                String orderId = sobj.getString("orderid");
                //
				//log
				ApiT_erp_log log = new ApiT_erp_log();

				log.setAction("wholesalersorder"+"_"+order_info.getTitles().trim()+"_"+bResult+"_"+sError+"_OrderId:"+orderId);
				log.setOrder_id(order_info.getTitles());
				log.setRemark(orderId);
				if(bResult=="true")
					log.setStatus(1);
				else
					log.setStatus(0);

				SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				log.setInvoke_time(sFormat.format(new Date()).toString());
				apiT_erp_logMapper.insertT_erp_log(log);
				
				if(bResult=="true"){
					ApiT_erp_log_hist log_hist = new ApiT_erp_log_hist();
					log_hist.setAction("wholesalersorder");
					log_hist.setOrder_id(order_info.getTitles());
					log_hist.setRemark(orderId);
					log_hist.setInvoke_time(sFormat.format(new Date()).toString());
					apiT_erp_log_histMapper.insertT_erp_log_hist(log_hist);
				}
                
            }else{
            	logger.error("erp调用返回编码："+response.getStatusLine().getStatusCode());
            }
        } catch (Exception e) {  
        	e.printStackTrace();  
        	logger.error(Util.getStackTraceAsString(e));
        } 
	          
	}
	
	/**
	 *ERP库存接口
	 */
	public void productStock4erp(ApiT_products product_info) {
	
		HttpClient httpclient = new DefaultHttpClient();  
		String erp_service = sartOnLoadService.dictionaryMap().get("ERP_SERVICE");
        String erpUrl="http://139.196.106.94:8090/Services.ashx";  
        HttpPost httppost = new HttpPost(erp_service);  
        String strResult = "";  
          
        try {             
            Map<String, Object> map = new TreeMap<String, Object>();
            map.put("sToken", this.tokenGet());  
            map.put("action", "goodsstockandshelves");
            //分站id对应仓库id
            ApiShop shop = apiShopsMapper.findT_shopsById(product_info.getShop_id());
            String str_BranchNo = "00" + shop.getC_city_id().toString();
            map.put("sBranchNo", str_BranchNo);
            map.put("iPageIndex", "1");
            map.put("iPageSize", "100");
            //
			List<Object> goods_list = new ArrayList<Object>();
			if (product_info.getErp_product_id() == null){
				return ;
			}
	        goods_list.add(""+product_info.getErp_product_id().substring(1)+"");
            map.put("goodsIds", goods_list);
            
            //遍历集合
            String strString1 = "";	
            for (Iterator<String> it = map.keySet().iterator(); it.hasNext();) {
            	String _key = it.next();
            	strString1 +="&" + _key +"="+ map.get(_key);
            }  
            // 生成ERP md5 
            strString1 = strString1.substring(1);
            String strTemp = strString1.toUpperCase();
            String strTempMd5 = Tools.erpMD5(strTemp).toUpperCase();
            map.put("sMd5", strTempMd5);
            
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
            nameValuePairs.add(new BasicNameValuePair("param", JsonUtil.object2json(map)));  
  
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
			//
			HttpResponse response = null;
			response = httpclient.execute(httppost);
 
            if (response.getStatusLine().getStatusCode() == 200) {  
                /*读返回数据*/  
                String conResult = null;
				conResult = EntityUtils.toString(response.getEntity());
		
                JSONObject sobj = new JSONObject();  
                sobj = sobj.fromObject(conResult);  
                 
                String bResult = sobj.getString("bResult");  
                String sCode = sobj.getString("sCode");  
                String sError = sobj.getString("sError");  
                //
                if(bResult=="true"){
                	JSONArray stockArray  = sobj.getJSONArray("stocks");
                	if (stockArray.size() == 0){
                		product_info.setStore(0);
                    	apiT_productsMapper.updateProducts4erp(product_info);
                	}
                	
                	for (int i = 0; i < stockArray.size(); i++){
                		JSONObject jsonObject = stockArray.getJSONObject(i);
                		
                		String erpGoodsId = jsonObject.getString("goodsId");
                		
                		//查找到与要更新的product一致的货品  （本地数据的product_id与erp的货品id最前面相差一个1）
                		if (product_info.getErp_product_id().substring(1).equals(erpGoodsId)){
                			String str_stock_cnt = jsonObject.getString("stockCnt");
                        	String str_shelves = jsonObject.getString("shelves");
                        	//返回的货位信息后面多了一个逗号 （如：121,）
                        	if (str_shelves != null && str_shelves.length() > 0){
                        		str_shelves = str_shelves.substring(0, str_shelves.length()-1);
                        	}
                        	if (Integer.valueOf(str_stock_cnt) >= 0){
                        		logger.error("Erp更新过来的库存信息-"+product_info.getProduct_id()+":库存="+str_stock_cnt);
                        		product_info.setStore(Integer.valueOf(str_stock_cnt));
                            	product_info.setErp_location(str_shelves);
                            	apiT_productsMapper.updateProducts4erp(product_info);
                        	}else{//为负数时,删除这个goods下面的product,并且如果这个goods下面的没有了product进行下线操作
                        		product_info.setStore(0);
                            	product_info.setErp_location(str_shelves);
                            	product_info.setIs_delete(1);
                            	apiT_productsMapper.updateProducts4erp(product_info);
                            	
                            	List<ApiT_products> products = apiT_productsService
                    					.getUndeletedProductsByGoodsId(product_info.getGoods_id());
                            	if (products.isEmpty()){//没有其它product时下架goods
                            		ApiGoods goods = new ApiGoods();
                            		goods.setGoods_id(product_info.getGoods_id());
                            		goods.setStatus("2");
                            		apiGoodsMapper.updateGoods(goods);
                            	}
                        	}
                		}else{
                			
                		}
                		
                	}
                	/*String str_stock_list = sobj.getString("stocks");
                	
                	str_stock_list= str_stock_list.replace("[", "").replace("]", "");
                	sobj = sobj.fromObject(str_stock_list); 
           
                	String str_stock_cnt = sobj.getString("stockCnt");
                	String str_shelves = sobj.getString("shelves");
                	
                	product_info.setStore(Integer.valueOf(str_stock_cnt));
                	product_info.setErp_location(str_shelves);
                	apiT_productsMapper.updateProducts4erp(product_info);*/
                }
				//log
				ApiT_erp_log log = new ApiT_erp_log();
				log.setAction("GoodsStock");
				log.setGoods_id(product_info.getErp_goods_sn());
				log.setProducts_id(product_info.getErp_product_id());
				SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
				log.setInvoke_time(sFormat.format(new Date()).toString());
				apiT_erp_logMapper.insertT_erp_log(log);
				
				// other citys  change by @RuanCong 2016/03/08 先不同步其它城市的库存
			/*	List<ApiT_city> citys = apiT_cityMapper.findT_citys();
				for(ApiT_city city : citys){
					// 其它分站是否有库存 
					if(city.getId().intValue() != Integer.valueOf(str_BranchNo)){
						ApiT_products other_new_product = product_info;
						other_new_product.setCity_id(city.getId());
						// 更新检查其它分站库存 
						this.productStock4OtherCitys(other_new_product);
					}
				}*/
				// end other citys
            }
        } catch (Exception e) {  
        	e.printStackTrace();  
        } 
	          
	}
	
	/**
	 *ERP库存接口
	 */
	public void productStock4OtherCitys(ApiT_products product_info) {
	
		HttpClient httpclient = new DefaultHttpClient();  
		String erp_service = sartOnLoadService.dictionaryMap().get("ERP_SERVICE");
        String erpUrl="http://139.196.106.94:8090/Services.ashx";  
        HttpPost httppost = new HttpPost(erp_service);  
        String strResult = "";  
          
        try {             
            Map<String, Object> map = new TreeMap<String, Object>();
            map.put("sToken", this.tokenGet());  
            map.put("action", "GoodsStock");
            //分站id对应仓库id
            String str_BranchNo = "00" + product_info.getCity_id().toString();
            map.put("sBranchNo", str_BranchNo);
            map.put("iPageIndex", "1");
            map.put("iPageSize", "100");
            //
			List<Object> goods_list = new ArrayList<Object>();
	        goods_list.add(""+product_info.getErp_product_id().substring(1)+"");
            map.put("goodsIds", goods_list);
            
            //遍历集合
            String strString1 = "";	
            for (Iterator<String> it = map.keySet().iterator(); it.hasNext();) {
            	String _key = it.next();
            	strString1 +="&" + _key +"="+ map.get(_key);
            }  
            // 生成ERP md5 
            strString1 = strString1.substring(1);
            String strTemp = strString1.toUpperCase();
            String strTempMd5 = Tools.erpMD5(strTemp).toUpperCase();
            map.put("sMd5", strTempMd5);
            
            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
            nameValuePairs.add(new BasicNameValuePair("param", JsonUtil.object2json(map)));  
  
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
			//
			HttpResponse response = null;
			response = httpclient.execute(httppost);
 
            if (response.getStatusLine().getStatusCode() == 200) {  
                /*读返回数据*/  
                String conResult = null;
				conResult = EntityUtils.toString(response.getEntity());
		
                JSONObject sobj = new JSONObject();  
                sobj = sobj.fromObject(conResult);  
                 
                String bResult = sobj.getString("bResult");  
                String sCode = sobj.getString("sCode");  
                String sError = sobj.getString("sError");  
                int stock_cnt = 0;
                //
                if(bResult=="true"){
                	//change by @RuanCong 2016/03/08  改成循环数组   （原先的注释掉了）
                    JSONArray stockArray  = sobj.getJSONArray("stocks");
                	for (int i = 0; i < stockArray.size(); i++){
                		JSONObject jsonObject = stockArray.getJSONObject(i);
                		
                		String erpGoodsId = jsonObject.getString("goodsId");
                		
                		//查找到与要更新的product一致的货品  （本地数据的product_id与erp的货品id最前面相差一个1）
                		if (product_info.getErp_product_id().substring(1).equals(erpGoodsId)){
                			String str_stock_cnt = jsonObject.getString("stockCnt");
                        	stock_cnt =Integer.valueOf(str_stock_cnt);
                		}else{
                			
                		}
                		
                	}
                	/*String str_stock_list = sobj.getString("stocks");
                	str_stock_list= str_stock_list.replace("[", "").replace("]", "");
                	sobj = sobj.fromObject(str_stock_list); 
           
                	String str_stock_cnt = sobj.getString("stockCnt");
                	stock_cnt =Integer.valueOf(str_stock_cnt);*/
                }		
				// insert other new stock to t_products
				ApiT_products existed_product = apiT_productsMapper.findProductByCityId_ErpProductId(product_info.getCity_id(), product_info.getErp_product_id());
				if(existed_product==null){
					ApiT_products t_product = new ApiT_products();
					//t_product.setProduct_id(0);
					t_product.setGoods_id(product_info.getGoods_id());
					t_product.setMkt_price(product_info.getMkt_price());
					t_product.setPrice(product_info.getPrice());
					t_product.setPdt_spec(product_info.getPdt_spec());
					t_product.setUnit(product_info.getUnit());
					t_product.setStore(stock_cnt);
					
					t_product.setErp_product_id(product_info.getErp_product_id());
					t_product.setErp_goods_sn(product_info.getErp_goods_sn());
					// ERP里 基础资料没有机构编码 city_id
					t_product.setCity_id(product_info.getCity_id());
					ApiShop _shop = apiShopsMapper.searchShopsZiYingByCityId(product_info.getCity_id().toString());
					t_product.setShop_id(_shop.getcId());
					apiT_productsMapper.insertT_products(t_product);
					
					//log
					ApiT_erp_log log2 = new ApiT_erp_log();
					log2.setAction("GoodsStock_Other_Products");
					log2.setGoods_id(product_info.getErp_goods_sn());
					log2.setProducts_id(product_info.getErp_product_id());
					SimpleDateFormat sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					sFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
					log2.setInvoke_time(sFormat.format(new Date()).toString());
					apiT_erp_logMapper.insertT_erp_log(log2);
				}
                // end insert other new stock to t_products
            }
        } catch (Exception e) {  
        	e.printStackTrace();  
        } 
	          
	}
	
	
	/**
	 * 获取Erp Token
	 * **/
	private String tokenGet(){
		
		Cache cache_config=  StartOnLoadService.manager.getCache("erp_token");  
	    Element element = cache_config.get("erp_token");
	    String result="";
	    
	    if(element==null){
			HttpClient httpclient = new DefaultHttpClient();  
	        String erpUrl="http://139.196.106.94:8090/Services.ashx";  
	        HttpPost httppost = new HttpPost(erpUrl);  
	          
	        try {            
	            Map<String, String> map = new TreeMap<String, String>();
	            map.put("action", "getToken");
	            map.put("sAppKey", "EDDJ");
	            map.put("sAppCode", "Bw8848@151228");
	
	            //遍历集合
	            String strString1 = "";	
	            for (Iterator<String> it = map.keySet().iterator(); it.hasNext();) {
	            	String _key = it.next();
	            	strString1 +="&" + _key +"="+ map.get(_key);
	            }
	 
	            // 生成ERP md5 
	            strString1 = strString1.substring(1);
	            String strTemp = strString1.trim().toUpperCase();
	            String strTempMd5 = Tools.erpMD5(strTemp).toUpperCase();
	            map.put("sMd5", strTempMd5);
	            
	            List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();  
	            nameValuePairs.add(new BasicNameValuePair("param", JsonUtil.object2json(map)));            
				httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs,"UTF-8"));
				//
				HttpResponse response = null;
				response = httpclient.execute(httppost);
	 
	            if (response.getStatusLine().getStatusCode() == 200) {  
	                /*读返回数据*/  
	                String conResult = null;
					conResult = EntityUtils.toString(response.getEntity());
			
	                JSONObject sobj = new JSONObject();  
	                sobj = sobj.fromObject(conResult);  
	                 result = sobj.getString("sToken");  
	                String code = sobj.getString("bResult");  
	                String error = sobj.getString("sCode");  
	                String sError = sobj.getString("sError"); 
	                // caching
	                cache_config.put(new Element("erp_token",result));  
	                
	            }
	        } catch (Exception e) {  
	        	e.printStackTrace();  
	        } 
	    }else{
	    	result = (String) element.getValue();
		}
	    
	    return result;      
	}
	
	//订单生成时 自营订单，通知ERP 并更新库存
	@Override
	public void newOrderToErp(ApiDingDan dingDan) {
		try{
			if(dingDan!=null){
				//不是充值订单
				Integer orderType = dingDan.getOrderType();
				if(orderType!=1){//0-购物订单，1-充值订单 , 2-充值有礼,3-积分兑换,4-1元购
					Integer shop_id = dingDan.getShop_id();
					ApiShop shop = apiShopsMapper.findT_shopsById(shop_id);
					Integer is_ziying = shop.getIs_ziying();
					if(1==is_ziying){
						List<ApiT_erp_log_hist> hist_order = apiT_erp_log_histMapper.findT_erp_log_histsByOrder_id(dingDan.getTitles());
						if(hist_order==null || hist_order.size()<=0){
							logger.error("通知ERP订单信息------"+dingDan.getTitles());
							this.addOrder4erp(dingDan);
							//同步更新库存
							String product_ids = dingDan.getProduct_ids();
							if(!Util.isNull(product_ids)){
								String[] productArray = product_ids.split(",");
								if(!Util.isNull(productArray) && productArray.length>0){
									for(String product_id : productArray){
										ApiT_products cur_product = apiT_productsService.findT_productsById(Long.valueOf(product_id));
										productStock4erp(cur_product);
									}
									
								}
								
							}
						}
					}
				}
			}
		}catch(Exception e){
			logger.error(e);
		}
		
	}

}
